package com.danieltoms.gcSync.google.feed;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;
import net.rim.device.api.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.danieltoms.gcSync.GcSyncStore;
import com.danieltoms.gcSync.google.GoogleContact;
import com.danieltoms.gcSync.google.GoogleLoginException;
import com.danieltoms.io.HttpConnectionHelper;

public class GoogleCreateFeed
{
	public GoogleCreateFeed()
	{

	}

	protected String getFeedURL()
	{
		StringBuffer buf = new StringBuffer();
		buf.append("http://www.google.com/m8/feeds/contacts/");
		buf.append(GcSyncStore.instance().getEmail());
		buf.append("/base");
		return buf.toString();
	}

	static class PrepareRequest implements HttpConnectionHelper.Callback
	{

		private static final String APPLICATION_ATOM_XML = "application/atom+xml";
		private static final String CONTENT_TYPE = "Content-Type";
		private static final String EN_US = "en-US";
		private static final String ACCEPT_LANGUAGE = "Accept_Language";
		private static final String MIDP1 = "Profile/MIDP-1.0 Configuration/CLDC-1.0";
		private static final String USER_AGENT = "User-Agent";
		public static final Hashtable m_args = new Hashtable();

		public void prepareRequest(String originalURL, HttpConnection conn) throws IOException
		{

			conn.setRequestMethod(HttpConnection.POST);
			conn.setRequestProperty(CONTENT_TYPE, APPLICATION_ATOM_XML);
			conn.setRequestProperty(USER_AGENT, MIDP1);
			conn.setRequestProperty(ACCEPT_LANGUAGE, EN_US);

			conn.setRequestProperty("Authorization", "GoogleLogin auth=" + m_args.get("auth"));

		}

		public void preparePost(HttpConnection c) throws IOException
		{
			_contact.printXML(System.out);
			DataOutputStream os = c.openDataOutputStream();
			os.write("<?xml version=\"1.0\"?>\n".getBytes());
			_contact.printXML(os);
			os.flush();

		}
	}

	private PrepareRequest m_prepareRequest = new PrepareRequest();
	private static GoogleContact _contact = null;

	protected InputStream getFeedInputStream() throws GoogleLoginException, IOException
	{

		HttpConnection c = null;
		InputStream is = null;

		int rc = -1;

		m_prepareRequest.m_args.put("auth", GcSyncStore.instance().getAuthToken());

		c = HttpConnectionHelper.connect(getFeedURL(), m_prepareRequest);

		rc = c.getResponseCode();
		System.out.println("getFeedInputStream return code: " + rc);

		if (rc == HttpConnection.HTTP_UNAUTHORIZED)
		{
			// our auth token expired, login again and try a new one

			GoogleClientLoginFeed gcl = new GoogleClientLoginFeed();
			if (gcl.authenticate(GcSyncStore.instance().getEmail(), GcSyncStore.instance().getPassword()))
			{
				// try again
				m_prepareRequest.m_args.put("auth", GcSyncStore.instance().getAuthToken());

				c = HttpConnectionHelper.connect(getFeedURL(), m_prepareRequest);

				rc = c.getResponseCode();
				System.out.println("getFeedInputStream return code: " + rc);
				// if we fail again, our password must have changed
			}

		}
		// 201 means created ok.
		if (rc != 201)
			throw new IOException("Feed returned HTTP " + rc);

		is = c.openDataInputStream();

		return is;

	}

	public GoogleContact createContact(GoogleContact gc) throws GoogleLoginException, IOException,
	        ParserConfigurationException, SAXException
	{
		_contact = gc;
		gc.printXML(System.out);

		_contact = gc;
		InputStream is = this.getFeedInputStream();

		if (is == null)
			return null;

		// Build a document based on the XML file.
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();

		Document document = builder.parse(is);

		gc = new GoogleContact(document.getDocumentElement());

		return gc;
	}

	public void log(String log)
	{
		System.out.println(log);
	}

}
